package com.cml.batisext.core.repository.mybatis.base.sqlprovider;

import java.lang.reflect.Field;

import com.cml.batisext.core.repository.mybatis.annotations.DbField;
import com.cml.batisext.core.repository.mybatis.annotations.DbTable;
import com.cml.batisext.core.repository.mybatis.base.BaseDaoSqlProvider;

/**
 * 通用接口的selectCount方法的sql生成器
 * @author lwh
 *
 */
public class BaseDaoSelectCountSqlProvider extends BaseDaoSqlProvider{

	public String doBuildSql(Object param,Class<?> beanType) throws Exception {
		
		String tableName = beanType.getAnnotation(DbTable.class).table();
		
		Field beanFields[] = beanType.getDeclaredFields();
		String tmpColumnName = null;
		Class<?> tmpColumnType = null;
		String sqlWhere = "";
		boolean hasWhere = false;
		Object fieldValue = null;
		for(Field f : beanFields){
			DbField field = f.getAnnotation(DbField.class);
			//只对标注了为数据库字段的属性进行处理
			if(field == null){
				continue;
			}
			
			tmpColumnName = getColumnName(f, field);
			tmpColumnType = getColumnType(f, field);
			
			fieldValue = getColumnValue(param,f,beanType);
			
			if(fieldValue != null){
				hasWhere = true;
				sqlWhere += tmpColumnName + " = " + setupFieldValue(tmpColumnType,fieldValue) + " and ";
			}
			
			
		}
		String sql = "select count(*) ";
		sql += " from " + tableName ;
		if(hasWhere){
			sql +=" where " + sqlWhere.substring(0,sqlWhere.length() - 4);
		}
		return sql;
	}
	
}
